cmake_minimum_required(VERSION 2.8)
project(libhsby)

# 设置编译选项
set(CMAKE_CXX_STANDARD 11)
#set(CMAKE_VERBOSE_MAKEFILE ON)
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/../bin)
set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/../lib)
set(CMAKE_CXX_FLAGS "$ENV{CXXFLAAGS} -O1 -g -std=c++11 -Wall -Wno-deprecated -Werror -Wno-unused-function -Wno-builtin-macro-redefined")

#重新定义当前目标的源文件的__FILE__宏
function(RedefineFileMacro targetname)
    #获取当前目标的所有源文件
    get_target_property(source_files "${targetname}" SOURCES)
    #遍历源文件
    foreach(sourcefile ${source_files})
        #获取当前源文件的编译参数
        get_property(defs SOURCE "${sourcefile}"
                PROPERTY COMPILE_DEFINITIONS)
        #获取当前文件的绝对路径
        get_filename_component(filepath "${sourcefile}" ABSOLUTE)
        #将绝对路径中的项目路径替换成空,得到源文件相对于项目路径的相对路径
        string(REPLACE ${PROJECT_SOURCE_DIR}/ "" relpath ${filepath})
        #将我们要加的编译参数(__FILE__定义)添加到原来的编译参数里面
        list(APPEND defs "__FILE__=\"${relpath}\"")
        #重新设置源文件的编译参数
        set_property(
                SOURCE "${sourcefile}"
                PROPERTY COMPILE_DEFINITIONS ${defs}
        )
    endforeach()
endfunction()


# 编译库hsby
include_directories(include)
set(LIB_SRC)
file(GLOB LIB_SRC hsby/*.cc hsby/http/*.cc)
add_library(hsby SHARED ${LIB_SRC})
RedefineFileMacro(hsby)
target_link_libraries(hsby yaml-cpp)
target_link_libraries(hsby pthread)
target_link_libraries(hsby dl)

# 测试
set(LIB_LIB dl hsby pthread)
file(GLOB SRC_FILES test/*.cc example/*.cc)
foreach(SRC_FILE ${SRC_FILES})
    STRING(REGEX REPLACE ".+/(.+)\\..*" "\\1" TARGET ${SRC_FILE})
    MESSAGE(${TARGET})
    add_executable(${TARGET} ${SRC_FILE})
    target_link_libraries(${TARGET} ${LIB_LIB})
    RedefineFileMacro(${TARGET})
endforeach(SRC_FILE)